// pages/gk/gk_add.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    name: '',
    ratio: '',
    ratio_r: '',
    count: '',
    studio: '',
    studio_r: '',
    agent: '',
    agent_r: '',
    retainer: '',
    remaining_price: '',
    original_price: '',
    total_price: '',
    estimated_time: '',
    product_width: '',
    product_depth: '',
    product_height: '',
    material: '',
    is_payment: '',
    is_payment_r: '',
    is_goods_arrived: '',
    is_goods_arrived_r: '',

    show: false,
    columns: [],
    dict_data_list: [],

    result: [],
    current_field: '',
    current_field2: '',
    dict_material: [],

    fileList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$request.post('api/v1/dict/data/all', {}).then(ret => {
      ret.result.forEach(item => {
        item.text = item.dict_value
        item.value = item.dict_type
      })
      this.setData({
        dict_material: ret.result.filter(item => item.dict_type == 'dict_material'),
        dict_data_list: ret.result,
      })
      if (options.id) {
        wx.$request.post('api/v1/gk/info/get', {id: options.id}).then(ret => {
          console.log(ret);
          let gk = ret.result;
          
          let body = {
            id: options.id,
            name: gk.name,
            ratio: gk.ratio,
            count: gk.count,
            studio: gk.studio,
            agent: gk.agent,
            retainer: gk.retainer,
            remaining_price: gk.remaining_price,
            original_price: gk.original_price,
            total_price: gk.total_price,
            estimated_time: gk.estimated_time,
            product_width: gk.product_width,
            product_depth: gk.product_depth,
            product_height: gk.product_height,
            material: gk.material,
            is_payment: gk.is_payment,
            is_goods_arrived: gk.is_goods_arrived,
          }
          let ratioR = this.data.dict_data_list.find(item => item.dict_type == 'dict_ratio' && item.dict_key == gk.ratio)
          if (ratioR) {
            body.ratio_r = ratioR.dict_value
          }
          let studioR = this.data.dict_data_list.find(item => item.dict_type == 'dict_studio' && item.dict_key == gk.studio)
          if (studioR) {
            body.studio_r = studioR.dict_value
          }
          let agentR = this.data.dict_data_list.find(item => item.dict_type == 'dict_agent' && item.dict_key == gk.agent)
          if (agentR) {
            body.agent_r = agentR.dict_value
          }
          let is_paymentR = this.data.dict_data_list.find(item => item.dict_type == 'dict_yes_no' && item.dict_key == gk.is_payment)
          if (is_paymentR) {
            body.is_payment_r = is_paymentR.dict_value
          }
          let is_goods_arrivedR = this.data.dict_data_list.find(item => item.dict_type == 'dict_yes_no' && item.dict_key == gk.is_goods_arrived)
          if (is_goods_arrivedR) {
            body.is_goods_arrived_r = is_goods_arrivedR.dict_value
          }
          if(gk.material) {
            let arr = gk.material.split(',')
            arr.forEach(item => {
              item = parseInt(item)
            })
            body.result = arr;
          }
          let tempList = gk.images ? gk.images.split(',') : []
          body.fileList = [];
          tempList.forEach(item => {
            body.fileList.push({url: item})
          })
          this.setData(body)
        }).catch(err => {
          console.log(err);
        })
      }
    }).catch(err => {
      console.log(err);
    })
    console.log(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onClose() {
    this.setData({show:false,})
  },
  onChange(e) {
    console.log(e);
    let data = wx.$base.getData(e)
    console.log(data);
    if (data.field) {
      let body = {}
      if (Array.isArray(e.detail)) {
        body[data.field] = e.detail.join(',')
      } else {
        body[data.field] = e.detail
      }
      if (data.checkbox == 1 && data.field2) {
        body[data.field2] = e.detail;
      }
      this.setData(body)
    }
  },
  showPopup(e) {
    let data = wx.$base.getData(e)
    console.log(data);
    let list = this.data.dict_data_list.filter(item => item.dict_type == data.type)
    console.log(list);
    this.setData({
      show: true,
      current_field: data.field,
      current_field2: data.field2 || undefined,
      columns: list,
    })
  },
  onConfirm(e) {
    console.log(e);
    console.log(this.data.current_field);
    if (!this.data.current_field) {
      return;
    }
    let body = {
      [this.data.current_field]: e.detail.value.dict_key,
    }
    if (this.data.current_field2) {
      body[this.data.current_field2] = e.detail.value.dict_value;
    }
    this.setData(body)
    this.onClose()
  },
  afterRead(event) {
    let me = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'http://127.0.0.1:6191/api/v1/file/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        // 上传完成需要更新 fileList
        console.log(res);
        let obj = JSON.parse(res.data)
        me.data.fileList.push({url: obj.url})
        console.log(me.data.fileList);
        me.setData({
          fileList: me.data.fileList,
        })
      },
    });
  },
  onImageDelete(e) {
    let url = e.detail.file.url;
    let index = this.data.fileList.findIndex(item => item.url == url)
    if (index > -1) {
      this.data.fileList.splice(index, 1)
      this.setData({fileList: this.data.fileList})
    }
    console.log(e);
  },
  onSubmit() {
    if (!this.data.name) {
      wx.$model.toast({content: '请输入GK名称'})
      return;
    }
    if (!this.data.ratio) {
      wx.$model.toast({content: '请输入GK比例'})
      return;
    }
    if (!this.data.count) {
      wx.$model.toast({content: '请输入GK数量'})
      return;
    }
    if (!this.data.studio) {
      wx.$model.toast({content: '请输入GK工作室'})
      return;
    }
    if (!this.data.agent) {
      wx.$model.toast({content: '请输入GK代理'})
      return;
    }
    if (!this.data.retainer) {
      wx.$model.toast({content: '请输入定金'})
      return;
    }
    if (!this.data.remaining_price) {
      wx.$model.toast({content: '请输入剩余金额'})
      return;
    }
    if (!this.data.original_price) {
      wx.$model.toast({content: '请输入原价'})
      return;
    }
    if (!this.data.total_price) {
      wx.$model.toast({content: '请输入最终价格'})
      return;
    }
    if (!this.data.estimated_time) {
      wx.$model.toast({content: '请选择预计时间'})
      return;
    }
    if (!this.data.product_width) {
      wx.$model.toast({content: '请输入产品宽度(mm)'})
      return;
    }
    if (!this.data.product_depth) {
      wx.$model.toast({content: '请选择产品深度(mm)'})
      return;
    }
    if (!this.data.product_height) {
      wx.$model.toast({content: '请选择产品高度(mm)'})
      return;
    }
    if (this.data.result.length === 0) {
      wx.$model.toast({content: '请选择GK材质'})
      return;
    }
    if (!this.data.is_payment) {
      wx.$model.toast({content: '请选择是否补款'})
      return;
    }
    if (!this.data.is_goods_arrived) {
      wx.$model.toast({content: '请选择是否到货'})
      return;
    }
    let body = {
      name: this.data.name,
      ratio: this.data.ratio,
      count: this.data.count,
      studio: this.data.studio,
      agent: this.data.agent,
      retainer: this.data.retainer,
      remaining_price: this.data.remaining_price,
      original_price: this.data.original_price,
      total_price: this.data.total_price,
      estimated_time: this.data.estimated_time,
      product_width: this.data.product_width,
      product_depth: this.data.product_depth,
      product_height: this.data.product_height,
      material: this.data.material,
      is_payment: this.data.is_payment,
      is_goods_arrived: this.data.is_goods_arrived,
    }
    let url = 'api/v1/gk/info/add'
    if (this.data.id) {
      body.id = this.data.id;
      url = 'api/v1/gk/info/upd'
    }
    console.log(body);
    body.images = this.data.fileList.map(item => item.url).join(',')
    wx.$request.post(url, body).then(ret => {
      console.log(ret);
      wx.$model.alert({content: '添加成功'}).then(() => {
        wx.$navigator.pop()
      })
    }).catch(err => {
      console.log(err);
    })
  }
})